package com.lancer.fileOperate.xml.sax;

import org.xml.sax.Attributes;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.DefaultHandler;
import java.util.ArrayList;
import java.util.List;

public class ServiceHandle extends DefaultHandler {
    private List<ServiceBean> services = null;
    private String tag; // 用于存储当前解析的标签名

    private ServiceBean serviceBean = null;


    public List<ServiceBean> getServices(){
        return services;
    }

    /**
     * 开始机械文档时调用，只会执行一次
     * @throws SAXException
     */
    @Override
    public void startDocument() throws SAXException{
        super.startDocument();
        services = new ArrayList<>();
        System.out.println("开始解析文档...");
    }

    @Override
    public void endDocument() throws  SAXException{
        super.endDocument();
        System.out.println("结束解析文档...");
    }


    /**
     * 开始解析标签时调用
     * @param url 命名空间
     * @param localName 不带前缀的标签名
     * @param qName 带前缀的标签名
     * @param attributes 当前标签属性
     * @throws SAXException
     */
    @Override
    public void startElement(String url, String localName, String qName, Attributes attributes) throws SAXException{
        super.startElement(url,localName,qName,attributes);
        if("service".equals(qName)){


            serviceBean = new ServiceBean();

        }
        tag = qName;
    }

    /**
     * 结束标签时调用
     * @param url 命名空间
     * @param localName 不带前缀的标签名
     * @param qName 带前缀的标签名
     * @throws SAXException
     */
    @Override
    public void endElement(String url, String localName, String qName) throws  SAXException{
        super.endElement(url,localName,qName);
        if("service".equals(qName)){
            services.add(serviceBean);
        }
        tag = null;
    }

    @Override
    public void characters(char[] ch ,int start, int length) throws  SAXException{
        super.characters(ch,start,length);
        if(tag != null){
            if("name".equals(tag)){
                serviceBean.setName(new String(ch,start,length));
            }
            if("uri".equals(tag)){
                serviceBean.setUri(new String(ch,start,length));
            }
            if("responseText".equals(tag)){
                serviceBean.setResponseText(new String(ch,start,length));
            }
            if("responseFile".equals(tag)){
                serviceBean.setResponseFile(new String(ch,start,length));
            }
        }
    }


}
